<template>
  <div class="player-ban-manage">
    <h2>玩家封禁管理</h2>
    <el-table :data="playerBans" style="width: 100%" border v-loading="loading">
      <el-table-column prop="id" label="封禁记录ID" align="center"></el-table-column>
      <el-table-column prop="playerId" label="玩家ID" align="center"></el-table-column>
      <el-table-column prop="startTime" label="封禁开始时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="封禁结束时间" align="center">
        <template #default="scope">
          {{ scope.row.endTime ? formatDate(scope.row.endTime) : '永久封禁' }}
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="封禁原因" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">解除封禁</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="showCreateDialog">封禁玩家</el-button>
      <el-button @click="fetchAllPlayerBans">查询所有封禁记录</el-button>
      <el-input
          v-model="searchPlayerId"
          placeholder="按玩家ID筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchPlayerBansByPlayerId"
      />
      <el-date-picker
          v-model="searchStartTime"
          type="date"
          placeholder="按开始时间筛选"
          style="width: 200px; margin-left: 10px"
          value-format="YYYY-MM-DD"
          @change="fetchPlayerBansByTime"
      ></el-date-picker>
      <el-date-picker
          v-model="searchEndTime"
          type="date"
          placeholder="按结束时间筛选"
          style="width: 200px; margin-left: 10px"
          value-format="YYYY-MM-DD"
          @change="fetchPlayerBansByTime"
      ></el-date-picker>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />
    </div>

    <!-- 封禁玩家表单对话框 -->
    <el-dialog title="封禁玩家" v-model="dialogVisible" width="30%">
      <el-form :model="playerBanForm" :rules="rules" ref="playerBanFormRef">
        <el-form-item label="玩家ID" prop="playerId">
          <el-input v-model="playerBanForm.playerId" />
        </el-form-item>
        <el-form-item label="封禁结束时间" prop="endTime">
          <el-date-picker
              v-model="playerBanForm.endTime"
              type="date"
              placeholder="选择封禁结束时间（若不选则为永久封禁）"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="封禁原因" prop="reason">
          <el-input v-model="playerBanForm.reason" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑封禁记录对话框 -->
    <el-dialog title="编辑封禁记录" v-model="editDialogVisible" width="30%">
      <el-form :model="editPlayerBanForm" :rules="rules" ref="editPlayerBanFormRef">
        <el-form-item label="玩家ID">
          <el-input v-model="editPlayerBanForm.playerId" disabled />
        </el-form-item>
        <el-form-item label="封禁结束时间" prop="endTime">
          <el-date-picker
              v-model="editPlayerBanForm.endTime"
              type="date"
              placeholder="选择封禁结束时间（若不选则为永久封禁）"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="封禁原因" prop="reason">
          <el-input v-model="editPlayerBanForm.reason" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updatePlayerBan">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

const playerBans = ref([]);
const loading = ref(false);
const searchPlayerId = ref('');
const searchStartTime = ref('');
const searchEndTime = ref('');

const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const isEdit = ref(false);

const playerBanForm = ref({
  id: null,
  playerId: '',
  endTime: null,
  reason: '',
  isPermanent: false // 新增字段，表示是否为永久封禁
});

const editPlayerBanForm = ref({
  id: null,
  playerId: '',
  endTime: null,
  reason: '',
  isPermanent: false
});

const playerBanFormRef = ref(null);
const editPlayerBanFormRef = ref(null);

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表单验证规则
const rules = reactive({
  playerId: [{ required: true, message: '请输入玩家ID', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入封禁原因', trigger: 'blur' }]
});

// 格式化日期为 YYYY-MM-DD HH:mm:ss
const formatDate = (dateString) => {
  if (!dateString) return '无';
  try {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    console.error('日期格式化错误:', error);
    return '时间格式错误';
  }
};

// 转换为后端需要的日期格式（ISO 8601）
const formatDateForApi = (dateString) => {
  if (!dateString) return null;
  try {
    // 转换为 ISO 8601 格式，如 2025-05-30T00:00:00Z
    return dayjs(dateString).toISOString();
  } catch (error) {
    console.error('API日期格式化错误:', error);
    return dateString;
  }
};

// 获取所有玩家封禁记录（分页）
const fetchAllPlayerBans = async () => {
  try {
    loading.value = true;

    // 构建请求参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      playerId: searchPlayerId.value.trim() || undefined,
      startTime: searchStartTime.value ? formatDateForApi(searchStartTime.value) : undefined,
      endTime: searchEndTime.value ? formatDateForApi(searchEndTime.value) : undefined
    };

    const response = await request.get('/customer-service/player-bans', { params });

    // 检查响应结构
    if (response.data && response.data.records) {
      playerBans.value = response.data.records.map(ban => ({
        ...ban,
        startTime: ban.startTime ? formatDate(ban.startTime) : null,
        endTime: ban.endTime ? formatDate(ban.endTime) : null,
        isPermanent: !ban.endTime // 添加是否永久封禁标记
      }));
      total.value = response.data.total || 0;
    } else {
      // 处理不同的响应结构
      console.warn('响应结构不符合预期:', response);
      playerBans.value = [];
      total.value = 0;

      if (response.message) {
        ElMessage.warning(response.message);
      }
    }
  } catch (error) {
    console.error('获取所有玩家封禁记录失败:', error);

    // 区分不同类型的错误
    if (error.response) {
      // 服务器返回错误状态码
      const status = error.response.status;
      const message = error.response.data?.message || `错误 ${status}`;

      if (status === 400) {
        ElMessage.error('请求参数错误: ' + message);
      } else if (status === 401) {
        ElMessage.error('未授权，请重新登录');
        // 跳转到登录页
      } else if (status === 403) {
        ElMessage.error('权限不足，无法执行此操作');
      } else if (status === 500) {
        ElMessage.error('服务器内部错误，请稍后再试');
      } else {
        ElMessage.error('请求失败: ' + message);
      }
    } else if (error.request) {
      // 请求已发送，但没有收到响应
      ElMessage.error('服务器无响应，请检查网络连接');
    } else {
      // 其他错误
      ElMessage.error('发生错误: ' + error.message);
    }
  } finally {
    loading.value = false;
  }
};

// 根据玩家ID获取玩家封禁记录（分页）
const fetchPlayerBansByPlayerId = async () => {
  const playerId = searchPlayerId.value.trim();
  if (!playerId) {
    ElMessage.warning('请输入玩家ID');
    return;
  }

  try {
    loading.value = true;
    const response = await request.get(`/customer-service/player-bans/player/${playerId}`, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });

    if (response.data && response.data.records) {
      playerBans.value = response.data.records.map(ban => ({
        ...ban,
        startTime: ban.startTime ? formatDate(ban.startTime) : null,
        endTime: ban.endTime ? formatDate(ban.endTime) : null,
        isPermanent: !ban.endTime
      }));
      total.value = response.data.total || 0;
    } else {
      playerBans.value = [];
      total.value = 0;
      ElMessage.info('未找到该玩家的封禁记录');
    }
  } catch (error) {
    console.error('获取玩家封禁记录失败:', error);
    handleApiError(error, '获取玩家封禁记录失败');
  } finally {
    loading.value = false;
  }
};

// 根据时间筛选获取玩家封禁记录（分页）
const fetchPlayerBansByTime = async () => {
  try {
    loading.value = true;

    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      playerId: searchPlayerId.value.trim() || undefined,
      startTime: searchStartTime.value ? formatDateForApi(searchStartTime.value) : undefined,
      endTime: searchEndTime.value ? formatDateForApi(searchEndTime.value) : undefined
    };

    const response = await request.get('/customer-service/player-bans', { params });

    if (response.data && response.data.records) {
      playerBans.value = response.data.records.map(ban => ({
        ...ban,
        startTime: ban.startTime ? formatDate(ban.startTime) : null,
        endTime: ban.endTime ? formatDate(ban.endTime) : null,
        isPermanent: !ban.endTime
      }));
      total.value = response.data.total || 0;
    } else {
      playerBans.value = [];
      total.value = 0;
      ElMessage.info('未找到符合条件的封禁记录');
    }
  } catch (error) {
    console.error('根据时间筛选获取玩家封禁记录失败:', error);
    handleApiError(error, '根据时间筛选获取玩家封禁记录失败');
  } finally {
    loading.value = false;
  }
};

// 统一处理API错误
const handleApiError = (error, defaultMessage) => {
  if (error.response) {
    const status = error.response.status;
    const message = error.response.data?.message || `错误 ${status}`;
    ElMessage.error(`${defaultMessage}: ${message}`);
  } else if (error.request) {
    ElMessage.error('请求超时，请检查网络连接');
  } else {
    ElMessage.error(`${defaultMessage}: ${error.message}`);
  }
};

// 显示封禁玩家对话框
const showCreateDialog = () => {
  dialogVisible.value = true;
  isEdit.value = false;
  playerBanForm.value = {
    id: null,
    playerId: '',
    endTime: null,
    reason: '',
    isPermanent: false
  };

  // 重置表单验证状态
  if (playerBanFormRef.value) {
    playerBanFormRef.value.resetFields();
  }
};

// 显示编辑对话框
const showEditDialog = (playerBan) => {
  editDialogVisible.value = true;
  isEdit.value = true;

  // 复制数据并处理日期格式
  editPlayerBanForm.value = {
    ...playerBan,
    // 将格式化后的日期转回原始格式
    startTime: playerBan.startTime ? dayjs(playerBan.startTime, 'YYYY-MM-DD HH:mm:ss').toISOString() : null,
    endTime: playerBan.endTime ? dayjs(playerBan.endTime, 'YYYY-MM-DD HH:mm:ss').toISOString() : null,
    isPermanent: !playerBan.endTime
  };

  // 重置表单验证状态
  if (editPlayerBanFormRef.value) {
    editPlayerBanFormRef.value.resetFields();
  }
};

// 提交封禁玩家表单
const submitForm = async () => {
  // 表单验证
  if (playerBanFormRef.value) {
    playerBanFormRef.value.validate((valid) => {
      if (!valid) return;

      // 处理表单数据
      const formData = {
        ...playerBanForm.value,
        // 如果未选择结束时间，则视为永久封禁
        isPermanent: !playerBanForm.value.endTime,
        // 转换日期格式为 ISO 8601
        endTime: playerBanForm.value.endTime
            ? formatDateForApi(playerBanForm.value.endTime)
            : null
      };

      // 发送请求
      createPlayerBan(formData);
    });
  } else {
    // 如果没有表单引用，则直接提交
    const formData = {
      ...playerBanForm.value,
      isPermanent: !playerBanForm.value.endTime,
      endTime: playerBanForm.value.endTime ? formatDateForApi(playerBanForm.value.endTime) : null
    };

    createPlayerBan(formData);
  }
};

// 创建封禁记录
const createPlayerBan = async (formData) => {
  try {
    const response = await request.post('/customer-service/player-bans', formData);

    if (response.code === 200) {
      ElMessage.success('封禁玩家成功');
      dialogVisible.value = false;
      // 刷新封禁记录列表
      await fetchAllPlayerBans();
    } else {
      ElMessage.error(response.message || '封禁玩家失败');
    }
  } catch (error) {
    console.error('封禁玩家出错:', error);
    handleApiError(error, '封禁玩家失败');
  }
};

// 提交编辑封禁记录表单
const updatePlayerBan = async () => {
  // 表单验证
  if (editPlayerBanFormRef.value) {
    editPlayerBanFormRef.value.validate((valid) => {
      if (!valid) return;

      // 处理表单数据
      const formData = {
        ...editPlayerBanForm.value,
        isPermanent: !editPlayerBanForm.value.endTime,
        endTime: editPlayerBanForm.value.endTime
            ? formatDateForApi(editPlayerBanForm.value.endTime)
            : null
      };

      // 发送请求
      savePlayerBan(formData);
    });
  } else {
    // 如果没有表单引用，则直接提交
    const formData = {
      ...editPlayerBanForm.value,
      isPermanent: !editPlayerBanForm.value.endTime,
      endTime: editPlayerBanForm.value.endTime ? formatDateForApi(editPlayerBanForm.value.endTime) : null
    };

    savePlayerBan(formData);
  }
};

// 保存封禁记录
const savePlayerBan = async (formData) => {
  try {
    const response = await request.put('/customer-service/player-bans', formData);

    if (response.code === 200) {
      ElMessage.success('更新封禁记录成功');
      editDialogVisible.value = false;
      // 刷新封禁记录列表
      await fetchAllPlayerBans();
    } else {
      ElMessage.error(response.message || '更新封禁记录失败');
    }
  } catch (error) {
    console.error('更新封禁记录出错:', error);
    handleApiError(error, '更新封禁记录失败');
  }
};

// 解除封禁
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要解除该玩家的封禁吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await request.delete(`/customer-service/player-bans/${id}`);

    if (response.code === 200) {
      ElMessage.success('解除封禁成功');
      // 刷新封禁记录列表
      await fetchAllPlayerBans();
    } else {
      ElMessage.error(response.message || '解除封禁失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解除封禁出错:', error);
      handleApiError(error, '解除封禁失败');
    }
  }
};

// 分页事件处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchAllPlayerBans();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchAllPlayerBans();
};

onMounted(() => {
  fetchAllPlayerBans();
});
</script>

<style scoped>
.player-ban-manage {
  padding: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
/* 添加表格加载状态样式 */
.el-table .el-loading-mask {
  z-index: 100;
}
</style>